extends TileMapLayer
class_name DrawPahtByMouseLayer

signal done_drawing_cells(cells:Array[Vector2i])

const DRAW_TILE_TYPE :Vector2i = Vector2i(2,0)
const DRAWING_BOARD_TILE_TYPE :Vector2i = Vector2i(1,0)

var is_drawing:bool

var mouse_cell:Vector2i
var start_draw_cell:Vector2i

var drawing_cell:Vector2i:
	set(new_cell):
		drawing_cell = new_cell
		drawable_cells = ShapeCells.get_diamond_cells(drawing_cell,1)
var drawable_cells:Array[Vector2i] = []

var drawn_cells:Array[Vector2i] = []

var drawable_board_cells:Array[Vector2i] = []

##画出线的长度，默认为-1。我们约定-1代表无限。
var path_longth:int = -1

func start_drawing_from_node(node2d:Node2D,_drawable_board_cells:Array[Vector2i],_path_longth:int = -1):
	var node2d_cell:Vector2i = local_to_map(node2d.position)
	start_drawing(node2d_cell,_drawable_board_cells,_path_longth)

func start_drawing(_start_cell:Vector2i,_drawable_board_cells:Array[Vector2i],_path_longth:int = -1):
	if is_drawing:
		return
	start_draw_cell = _start_cell
	drawing_cell = _start_cell
	
	drawable_board_cells = _drawable_board_cells
	
	_lay_drawing_board_cells()
	
	path_longth = _path_longth
	is_drawing = true
	_draw_cell(start_draw_cell)

func _end_drawing():
	is_drawing = false
	
	done_drawing_cells.emit(drawn_cells)
	_erase_drawing_board_cells()
	
	drawn_cells.clear()
	drawable_cells.clear()

func _process(delta: float) -> void:
	if !is_drawing:
		return
	if Input.is_action_pressed("mouse_click_left"):
		_get_mouse_cell()
		_draw_path()
	elif Input.is_action_just_released("mouse_click_left"):
		_end_drawing()

func _get_mouse_cell():
	mouse_cell = local_to_map(get_global_mouse_position())

func _draw_path():
	drawing_cell = drawn_cells.back()
	if mouse_cell == drawing_cell:
		return
	if !drawable_board_cells.has(mouse_cell):
		return
	
	if drawn_cells.has(mouse_cell):
		_erase_path_to_cell()
	elif drawable_cells.has(mouse_cell):
		_draw_cell(mouse_cell)

func _draw_cell(cell:Vector2i):
	if path_longth == 0:
		return
	set_cell(cell,0,DRAW_TILE_TYPE)
	drawn_cells.append(cell)
	path_longth -= 1

func _erase_path_to_cell():
	while drawn_cells.back() != mouse_cell:
		var temp_cell = drawn_cells.pop_back()
		set_cell(temp_cell,0,DRAWING_BOARD_TILE_TYPE)

func _lay_drawing_board_cells():
	for  temp_cell in drawable_board_cells:
		set_cell(temp_cell,0,DRAWING_BOARD_TILE_TYPE)

func _erase_drawing_board_cells():
	for temp_cell in drawable_board_cells:
		erase_cell(temp_cell)
